package com.lyfei.yd.system.service;

import com.lyfei.yd.system.domain.entity.Region;
import com.lyfei.yd.system.mapper.RegionMapper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("regionService")
public class RegionService extends BaseService<RegionMapper, Region> {
    public List<Region> getAll() {
        List<Region> regions = this.list();

        return regions.stream()
                .filter(region -> region.getPid() == 0)
                .peek((item) -> item.setChildren(getChildren(item, regions)))
                .sorted((item1, item2) -> (item1.getCode() == null ? 0 : item1.getCode()) - (item2.getCode() == null ? 0 : item2.getCode()))
                .collect(Collectors.toList());
    }

    private List<Region> getChildren(Region parent, List<Region> regions) {
        return regions.stream()
                .filter(region -> region.getPid().equals(parent.getId()))
                .peek((item) -> item.setChildren(getChildren(item, regions)))
                .sorted((item1, item2) -> (item1.getCode() == null ? 0 : item1.getCode()) - (item2.getCode() == null ? 0 : item2.getCode()))
                .collect(Collectors.toList());
    }
}
